# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning
from datetime import datetime


class Supplier(models.Model):
    """
    供应商
    """
    _name = "tyibs.main.supplier.supplier"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="名称", required=True, index=True)
    street = fields.Char(string="地址")
    contact = fields.Char(string="联系人")
    mobile = fields.Char(string="联系手机")
    phone = fields.Char(string="联系电话")
    fax = fields.Char(string="传真号码")
    remark = fields.Text(string="备注")


class ProductCategory(models.Model):
    """
    产品类型
    """
    _name = "tyibs.main.supplier.product.category"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="产品类型", required=True, index=True)
    remark = fields.Text(string="备注")


class ProductModel(models.Model):
    """
    产品规格
    """
    _name = "tyibs.main.supplier.product.model"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="产品规格", required=True, index=True)
    remark = fields.Text(string="备注")


class Product(models.Model):
    """
    产品计量单位管理
    """
    _name = "tyibs.main.supplier.product"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="产品名称", required=True, index=True)
    supplier_id = fields.Many2one("tyibs.main.supplier.supplier", string="供应商", required=True)
    category_id = fields.Many2one("tyibs.main.supplier.product.category", string="产品类型")
    model_id = fields.Many2one("tyibs.main.supplier.product.model", string="产品规格")
    price = fields.Float(string="单价")
    total_count = fields.Integer(string="数量")
    lowest_count = fields.Integer(string="最低库存")
    detail = fields.Text(string="详细信息")
    remark = fields.Text(string="备注")


class Warehourse(models.Model):
    """
    仓库
    """
    _name = "tyibs.main.supplier.warehourse"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="名称", required=True, index=True)
    street = fields.Char(string="地址")
    manager = fields.Char(string="仓库管理员")
    mobile = fields.Char(string="管理员手机")
    phone = fields.Char(string="管理员电话")
    rack_ids = fields.One2many("tyibs.main.supplier.warehourse.rack", "warehourse_id", string="货架")
    remark = fields.Text(string="备注")


class WarehourseRack(models.Model):
    """
    货架
    """
    _name = "tyibs.main.supplier.warehourse.rack"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    warehourse_id = fields.Many2one("tyibs.main.supplier.warehourse", string="仓库", required=True)
    name = fields.Char(string="名称", required=True, index=True)
    position = fields.Char(string="货架位置")
    remark = fields.Text(string="备注")


class StockIn(models.Model):
    """
    入库单
    """
    _name = "tyibs.main.supplier.warehourse.move.in"

    # 自动生成入库单号
    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char('入库单号', index=True, required=True)
    operator_user_id = fields.Many2one("res.users", string="入库人", default=lambda self:self.env.uid, domain="[('main_company_id','=',enterprise_id)]")
    operator_time = fields.Datetime(string="入库时间", default=lambda self:fields.Datetime.now())
    purchase_man = fields.Char(string="采购人")
    state = fields.Selection([('draft','未审核'),('approved','已审核')], string="审核状态", default="draft", required=True)
    check_user_id = fields.Many2one("res.users", string="审核人")
    check_time = fields.Datetime(string="审核时间")
    line_ids = fields.One2many("tyibs.main.supplier.warehourse.move.in.line","move_id", string="入库单详细", required=True)
    remark = fields.Text(string="备注")

    @api.multi
    def check_approved(self):
        """
        审核通过
        通过后将数量更新到对应的产品中
        """
        self.ensure_one()
        for item in self.line_ids:
            item.product_id.total_count = item.product_id.total_count + item.count
        return self.write({'state':'approved'})


class StockInLine(models.Model):
    """
    入库单详细
    """
    _name = "tyibs.main.supplier.warehourse.move.in.line"
    _rec_name = "product_id"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    move_id = fields.Many2one("tyibs.main.supplier.warehourse.move.in", string="入库单", required=True)
    product_id = fields.Many2one("tyibs.main.supplier.product", string="产品", required=True)
    product_model_id = fields.Many2one("tyibs.main.supplier.product.model",related="product_id.model_id",store=True)
    count = fields.Integer(string="入库数量", required=True)
    warehourse_id = fields.Many2one("tyibs.main.supplier.warehourse", string="仓库", required=True)
    rack_id = fields.Many2one("tyibs.main.supplier.warehourse.rack", string="货架", domain="[('warehourse_id','=', warehourse_id)]", required=True)


class StockOutCategory(models.Model):
    """
    出库类型: 派工、维保、销售、挂靠、借用、其他等
    """
    _name = "tyibs.main.supplier.warehourse.move.out.category"
    
    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char(string="出库类型", required=True, index=True)
    remark = fields.Text(string="备注")


class StockOut(models.Model):
    """
    出库单
    """
    _name = "tyibs.main.supplier.warehourse.move.out"

    # 自动生成入库单号
    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    name = fields.Char('出库单号', index=True, required=True)
    operator_user_id = fields.Many2one("res.users", string="出库人", default=lambda self:self.env.uid)
    operator_time = fields.Datetime(string="出库时间", default=lambda self:fields.Datetime.now())
    # TODO:只能选择本单位人员 
    take_emp_id = fields.Many2one("tyibs.base.maintenance.company.employee", string="领料人", domain="[]", required=True)
    out_category_id = fields.Many2one("tyibs.main.supplier.warehourse.move.out.category", string="出库类型", required=True)
    # 可能是维保，也可能是维修
    # TODO:看看是否要真正关联，还是只记录工单号
    order_so = fields.Char(string="关联的工单号")
    state = fields.Selection([('draft','未审核'),('approved','已审核')], string="审核状态", default="draft", required=True)
    check_user_id = fields.Many2one("res.users", string="审核人")
    check_time = fields.Datetime(string="审核时间")
    line_ids = fields.One2many("tyibs.main.supplier.warehourse.move.out.line","move_id", string="出库单详细", required=True)
    remark = fields.Text(string="备注")

    @api.multi
    def check_approved(self):
        """
        审核通过
        通过后将数量更新到对应的产品中
        """
        self.ensure_one()

        out_rep = self.env['tyibs.main.supplier.warehourse.move.out.line']
        in_rep = self.env['tyibs.main.supplier.warehourse.move.in.line']

        for line in self.line_ids:
            out_records = out_rep.search([('rack_id', '=', line.rack_id.id), ('product_id', '=', line.product_id.id), ('move_id.state', '=', 'approved')])
            in_records = in_rep.search([('rack_id', '=', line.rack_id.id), ('product_id', '=', line.product_id.id), ('move_id.state', '=', 'approved')])
            in_total_count = sum(line.count for line in in_records)
            out_total_count = sum(line.count for line in out_records)
            left_count = in_total_count - out_total_count
            if line.count > left_count:
                raise ValidationError("货架{0}下产品存量不足,仅余{1}".format(line.rack_id.name,left_count))

        for item in self.line_ids:
            item.product_id.total_count = item.product_id.total_count - item.count
        return self.write({'state':'approved'})


class StockOutLine(models.Model):
    """
    出库单详细
    """
    _name = "tyibs.main.supplier.warehourse.move.out.line"
    _rec_name = "product_id"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string="维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    move_id = fields.Many2one("tyibs.main.supplier.warehourse.move.out", string="出库单", required=True)
    product_id = fields.Many2one("tyibs.main.supplier.product", string="产品", required=True)
    product_model_id = fields.Many2one("tyibs.main.supplier.product.model",related="product_id.model_id",store=True)
    count = fields.Integer(string="出库数量", required=True)
    warehourse_id = fields.Many2one("tyibs.main.supplier.warehourse", string="仓库", required=True)
    rack_id = fields.Many2one("tyibs.main.supplier.warehourse.rack", string="货架", domain="[('warehourse_id','=', warehourse_id)]", required=True)

    @api.onchange("count")
    def on_change_out_count(self):
        self.ensure_one()
        out_rep = self.env['tyibs.main.supplier.warehourse.move.out.line']
        in_rep = self.env['tyibs.main.supplier.warehourse.move.in.line']
        if not self.rack_id:
            self.count = 0
        else:
            out_records = out_rep.search([('rack_id', '=', self.rack_id.id), ('product_id', '=', self.product_id.id), ('move_id.state', '=', 'approved')])
            in_records = in_rep.search([('rack_id', '=', self.rack_id.id), ('product_id', '=', self.product_id.id), ('move_id.state', '=', 'approved')])
            in_total_count = sum(line.count for line in in_records)
            out_total_count = sum(line.count for line in out_records)
            left_count = in_total_count - out_total_count
            if self.count > left_count:
                raise ValidationError("货架{0}下产品存量不足,仅余{1}".format(self.rack_id.name,left_count ))

